package io.github.service.excel.listener;


import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import io.github.constant.Constant;
import io.github.entity.ExtensionEntity;
import io.github.pojo.ExtensionPojo;
import io.github.service.AnswerGroupService;
import io.github.service.ExtensionService;
import io.github.service.impl.AnswerGroupServiceImpl;
import io.github.util.CommandUtils;
import org.apache.log4j.Logger;

import java.util.Date;

/**
 * @author Max
 * <br>
 * date 2019/12/28 11:41
 */

public class ExtensionListener extends AnalysisEventListener<ExtensionPojo> {

    static Logger logger = Logger.getLogger(ExtensionEntity.class);

    ExtensionService extensionService = null;
    AnswerGroupService answerGroupService = null;

    public ExtensionListener(ExtensionService extensionService, AnswerGroupService answerGroupService) {
        this.extensionService = extensionService;
        this.answerGroupService =  answerGroupService;
    }

    @Override
    public void invoke(ExtensionPojo pojo, AnalysisContext analysisContext) {
        try {

            ExtensionEntity entity = new ExtensionEntity();
            entity.setNumber(pojo.getNumber());
            entity.setPassword(pojo.getPassword());
            entity.setUnconditionalTransfer(pojo.getUnconditionalTransfer());
            entity.setUnreplyTransfer(pojo.getUnreplyTransfer());
            entity.setBusyTransfer(pojo.getBusyTransfer());
            entity.setDisplayCaller(pojo.getDisplayCaller());
            entity.setDndTransfer("开启".equals(pojo.getDndTransfer())?"1":"");
            entity.setCount(pojo.getCount());
            entity.setClockTime(pojo.getClockTime());
            entity.setAnswerGroup(answerGroupService.getByName(pojo.getGroupName()).getId());
            entity.setRecordSound("是".equals(pojo.getRecordSound()));
            if(Constant.AUTH_CITY.equals(pojo.getAuth())){
                entity.setAuth(1);
            } else if(Constant.AUTH_INNER.equals(pojo.getAuth())){
                entity.setAuth(2);
            } else if(Constant.AUTH_OUTER.equals(pojo.getAuth())) {
                entity.setAuth(3);
            } else if(Constant.AUTH_GROUP.equals(pojo.getAuth())) {
                entity.setAuth(4);
            }
            entity.setCreateTime(new Date());
            extensionService.save(entity);
            CommandUtils.exeAdd(pojo.getNumber(),pojo.getPassword(),pojo.getGroupName());
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("这一条数据保存失败");
        }
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {
        logger.info("数据解析完成");
    }

}